package 代理模式;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Utils {
    public static <T> T getInstance(Class targetClass,Class<T> proxyInterfaceClass,BeforeAndAfter action) throws IllegalAccessException, InstantiationException {
        Object target = targetClass.newInstance();//目标对象
        Object proxyInstance = Proxy.newProxyInstance(targetClass.getClassLoader(),
                new Class[]{proxyInterfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        action.befoer();
                        Object rel = method.invoke(target, args);//执行目标对象的方法,args是目标对象方法的参数
                        action.after();

                        return rel;
                    }
                }
        );
        return (T)proxyInstance;
    }
}
